#include "Accpetor.hpp"
#include <asm-generic/socket.h>
#include <sys/socket.h>
#include <unistd.h>

namespace wd{
Acceptor::Acceptor(int port, string ip):
_addr(port,ip)
,_sock(){

}


void Acceptor::ready(){
    setReusetAddr(true);
    setReusetPort(true);
    
    bind();
    listen();
    printf("start listen\n");
}

int Acceptor::accept(){
    int clientfd = ::accept(_sock.fd(),NULL,NULL);
    return clientfd;
}

void Acceptor::setReusetAddr(bool flag){
    if(flag){
        int on = 1;
        setsockopt(_sock.fd(),SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
    }
}

void Acceptor::setReusetPort(bool flag){
    if(flag){
        int on = 1;
        setsockopt(_sock.fd(),SOL_SOCKET,SO_REUSEPORT,&on,sizeof(on));
    }
}

void Acceptor::bind(){
    int ret = ::bind(_sock.fd(),(struct sockaddr*)_addr.getInetAddrptr(),sizeof(_addr));
    if(ret < 0){
        perror("bind");
    }
}   

void Acceptor::listen(){
    int ret = ::listen(_sock.fd(),100);
    if(ret < 0){
        perror("listen");
    }
}

}
